package com.koron.tool.frame;

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.Vector;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import com.koron.mybatis.SessionFactory;
import com.koron.tool.MainFrame;
import com.koron.ui.MutableGridLayout;
import com.koron.web.bean.EnumDBBean;
import com.koron.web.bean.EnumDetailDBBean;
import com.koron.web.mapper.UserDefineMapper;

/**
 * 用户自定义界面
 * 
 * @author swan
 *
 */
public class EnumFrame extends JInternalFrame {

	private static EnumFrame instance;

	private DefaultTableModel dtm = new DefaultTableModel(new String[] { "ID", "key" }, 0);
	private DefaultTableModel dtm2 = new DefaultTableModel(new String[] { "KEY", "Value" }, 1);

	private JSplitPane split;
	/**
	 * 字段
	 */
	private final JTable jtb = new JTable(dtm) {
		public boolean isCellEditable(int row, int column) {
			return false;
		}
	};

	private final JTable jtbEnumItem = new JTable(dtm2);

	// 以下为字段的属性
	private JPanel enumPanel = new JPanel();
	private JTextField jtfID = new JTextField();
	private JTextField jtfName = new JTextField();
	private JTextField jtfParam = new JTextField();
	private JCheckBox jcbIsBit = new JCheckBox("是否位值");
	private JCheckBox jcbString = new JCheckBox("字符串");
	private JCheckBox jcbInteger = new JCheckBox("整型");
	private JCheckBox jcbLong = new JCheckBox("长整型");
	private ButtonGroup group;

	public MainFrame frame;

	public static synchronized EnumFrame getInstance(MainFrame frame) {
		if (instance != null && !instance.isClosed)
			return instance;
		instance = new EnumFrame(frame);
		return instance;
	}

	private EnumFrame(MainFrame frame) {
		super("数据库设置");
		this.frame = frame;
		setSize(800, 600);
		setMaximizable(true);
		setClosable(true);
		setIconifiable(true);
		setResizable(true);
		JPanel panel = enumPanel;
		MutableGridLayout layout = new MutableGridLayout(4, 5, 5, 5);
		layout.setHeight(0, 30);
		layout.setHeight(1, 30);
		layout.setHeight(2, 30);
		layout.setHeight(4, 30);
		layout.merge(1, 1, 3, 1);
		layout.merge(0, 3, 3, 3);
		layout.setWidth(0, 80);
		layout.setWidth(2, 80);
		panel.setLayout(layout);
		panel.add(new JLabel("ID"));
		panel.add(jtfID);
		panel.add(new JLabel("名称"));
		panel.add(jtfName);
		panel.add(new JLabel("参数"));
		panel.add(jtfParam);
		panel.add(jcbIsBit);
		panel.add(jcbString);
		panel.add(jcbInteger);
		panel.add(jcbLong);
		group = new ButtonGroup();
		jcbString.setActionCommand("0");
		jcbInteger.setActionCommand("1");
		jcbLong.setActionCommand("2");
		group.add(jcbString);
		group.add(jcbInteger);
		group.add(jcbLong);
		JScrollPane jsp = new JScrollPane(jtbEnumItem);
		jsp.addMouseListener(new MouseAdapter() {
			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent
			 * )
			 */
			@Override
			public void mouseClicked(MouseEvent e) {
				super.mouseClicked(e);
				if (dtm2.getRowCount() == 0)
					dtm2.setRowCount(1);
			}
		});
		jtbEnumItem.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
				if (jtbEnumItem.getSelectedRow() != -1 && jtbEnumItem.getSelectedRow() + 1 == dtm2.getRowCount()) {
					dtm2.setRowCount(dtm2.getRowCount() + 1);
				}
			}
		});
		jtbEnumItem.addMouseListener(new MouseAdapter() {
			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent
			 * )
			 */
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON3)// 右键增加删除
				{
					JPopupMenu menu = new JPopupMenu();
					menu.add(new JMenuItem(new RemoveItem(jtbEnumItem, e.getX(), e.getY(), dtm2)));
					menu.show(jtbEnumItem, e.getX(), e.getY());
				}
			}
		});

		jsp.setPreferredSize(new Dimension(10, 10));
		panel.add(jsp);
		panel.add(new JButton(new SaveAction(this)));
		split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(jtb), enumPanel);
		split.setDividerSize(10);
		split.setDividerLocation(200);
		split.setResizeWeight(0.2);
		getContentPane().add(split);
		jtb.getColumnModel().getColumn(0).setWidth(100);
		jtb.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
			@Override
			public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
					boolean hasFocus, int row, int column) {
				if (value instanceof EnumDBBean)
					value = ((EnumDBBean) value).getId();
				return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
			}
		});
		jtb.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer() {
			@Override
			public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
					boolean hasFocus, int row, int column) {
				if (value instanceof EnumDBBean)
					value = ((EnumDBBean) value).getKey();
				return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
			}
		});
		jtb.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent e) {
				if (jtb.getSelectedRow() == -1)
					return;
				Object o = dtm.getValueAt(jtb.getSelectedRow(), 0);
				if (o instanceof EnumDBBean) {
					loadDBBean((EnumDBBean) o);
				}
			}
		});
		jtb.addMouseListener(new MouseAdapter() {
			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent
			 * )
			 */
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON3)// 右键增加删除
				{
					JPopupMenu menu = new JPopupMenu();
					menu.add(new JMenuItem(new DeleteEnumAction(jtb, e.getX(), e.getY(), dtm)));
					menu.show(jtb, e.getX(), e.getY());
				}
			}
		});
		loadEnum();
		jtb.setRowHeight(30);
		jtbEnumItem.setRowHeight(30);
		setVisible(true);
	}

	private void loadEnum() {
		dtm.setRowCount(0);
		SessionFactory factory = new SessionFactory();
		UserDefineMapper mapper = factory.getMapper(UserDefineMapper.class);
		List<EnumDBBean> list = mapper.listEnum();
		for (EnumDBBean enumDBBean : list) {
			dtm.addRow(new Object[] { enumDBBean, enumDBBean });
		}
		factory.close();
	}

	private void loadDBBean(EnumDBBean bean) {
		jtfID.setText(String.valueOf(bean.getId()));
		jtfName.setText(bean.getKey());
		jtfParam.setText(bean.getParam());
		if (bean.getIsbit())
			jcbIsBit.setSelected(true);
		else
			jcbIsBit.setSelected(false);
		switch (bean.getType()) {
		case 0:
			jcbString.setSelected(true);
			break;
		case 1:
			jcbInteger.setSelected(true);
			break;
		case 2:
			jcbLong.setSelected(true);
			break;
		}
		SessionFactory factory = new SessionFactory();
		UserDefineMapper mapper = factory.getMapper(UserDefineMapper.class);
		List<EnumDetailDBBean> list = mapper.getEnumDetailByEnumId(bean.getId());
		dtm2.setRowCount(0);
		for (EnumDetailDBBean enumDetailDBBean : list) {
			dtm2.addRow(new String[] { enumDetailDBBean.getKey(), enumDetailDBBean.getValue() });
		}
		factory.close();
	}

	class SaveAction extends AbstractAction {
		EnumFrame frame;

		public SaveAction(EnumFrame frame) {
			super();
			putValue(NAME, "保存");
			putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
			this.frame = frame;
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			EnumDBBean bean = new EnumDBBean();
			bean.setId(Integer.valueOf(jtfID.getText()));
			bean.setIsbit(jcbIsBit.isSelected());
			bean.setKey(jtfName.getText());
			bean.setParam(jtfParam.getText());
			bean.setType(Integer.parseInt(group.getSelection().getActionCommand()));
			SessionFactory factory = new SessionFactory();
			UserDefineMapper mapper = factory.getMapper(UserDefineMapper.class);
			if (bean.getId() != -1)
				mapper.updateEnum(bean);
			else
				mapper.addEnum(bean);
			mapper.deleteEnumItemByEnumId(bean.getId());
			for (Object row : dtm2.getDataVector()) {
				Vector<?> rowData = (Vector<?>) row;
				EnumDetailDBBean item = new EnumDetailDBBean();
				item.setEnumid(bean.getId());
				item.setKey(String.valueOf(rowData.get(0)));
				item.setValue(String.valueOf(rowData.get(1)));
				if (item.getKey() != null && !item.getKey().isEmpty() && !item.getKey().equals("null"))
					mapper.addEnumItem(item);
			}
			JOptionPane.showMessageDialog(frame, "枚举变更完成。");
			factory.close();
			loadEnum();
		}
	}

	class RemoveItem extends AbstractAction {
		JTable jtbEnumItem;
		int x;
		int y;
		DefaultTableModel dtm2;
		public RemoveItem(JTable jtbEnumItem, int x, int y, DefaultTableModel dtm2) {
			this.x = x;
			this.y = y;
			this.jtbEnumItem = jtbEnumItem;
			this.dtm2 = dtm2;
			putValue(NAME, "移除");
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			int row = jtbEnumItem.rowAtPoint(new Point(x,y));
			if(JOptionPane.showConfirmDialog(frame, "是否要删除枚举值:"+jtbEnumItem.getValueAt(row, 0),"",JOptionPane.OK_CANCEL_OPTION)!=JOptionPane.OK_OPTION)
				return;
			SessionFactory factory = new SessionFactory();
			UserDefineMapper mapper = factory.getMapper(UserDefineMapper.class);
			List<EnumDetailDBBean> list = mapper.getEnumDetailByEnumId(Integer.parseInt(jtfID.getText()));
			for (EnumDetailDBBean enumDetailDBBean : list) {
				if(enumDetailDBBean.getKey().equals(dtm2.getValueAt(row, 0)))
				{
					mapper.deleteEnumItem(enumDetailDBBean.getId());
					break;
				}
			}
			dtm2.removeRow(row);
			factory.close();
		}
	}
	class DeleteEnumAction extends AbstractAction {
		
		JTable table;int x;int y;DefaultTableModel model;
		public DeleteEnumAction(JTable table,int x,int y,DefaultTableModel model) {
			super();
			this.table = table;
			this.x = x;
			this.y = y;
			this.model = model;
			putValue(NAME, "删除");
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			int row = table.rowAtPoint(new Point(x,y));
			if(row == -1)
				return;
			EnumDBBean bean =(EnumDBBean)table.getValueAt(row, 1);
			 
			if(JOptionPane.showConfirmDialog(frame, "是否要删除此枚举"+bean.getKey(),"",JOptionPane.OK_CANCEL_OPTION)!=JOptionPane.OK_OPTION)
				return;
			SessionFactory factory = new SessionFactory();
			UserDefineMapper mapper = factory.getMapper(UserDefineMapper.class);
			
			mapper.deleteEnumItemByEnumId(bean.getId());
			mapper.deleteEnum(bean.getId());
			model.removeRow(row);
			JOptionPane.showMessageDialog(frame, "删除枚举完成。");
			factory.close();
			loadEnum();
		}
	}
}
